package pl.register.android.activities.correlation.ui;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import pl.register.android.R;
import pl.register.android.activities.correlation.logic.SelectedStudentsHolder;
import pl.register.android.student.Student;
import pl.register.android.util.StringUtils;
import pl.register.android.widget.listview.RefreshableAdapter;

import java.util.ArrayList;

/**
 * @author Mateusz Strzelecki
 * @since 0.0.1
 */
public class StudentsChoiceListAdapter extends RefreshableAdapter<Student> {

    private SelectedStudentsHolder selectedStudentsHolder;

    public StudentsChoiceListAdapter(Context ctx, SelectedStudentsHolder selectedStudentsHolder) {
        super(ctx, new ArrayList<Student>());
        this.selectedStudentsHolder = selectedStudentsHolder;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.dialog_list_row_student_chooser, null);
            holder.ctvStudent = (CheckedTextView) convertView.findViewById(R.id.student_text_view);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Student student = getItem(position);
        holder.ctvStudent.setText(StringUtils.build(student.getFirstName(), " ", student.getLastName(), " - ", student.getCity()));
        holder.ctvStudent.setChecked(selectedStudentsHolder.contains(student));
        holder.ctvStudent.setFocusable(false);
        holder.ctvStudent.setClickable(false);
        return convertView;
    }

    public boolean toggleItem(View view) {
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.ctvStudent.toggle();
        return holder.ctvStudent.isChecked();
    }

    public boolean isChecked(View view) {
        ViewHolder holder = (ViewHolder) view.getTag();
        return holder.ctvStudent.isChecked();
    }

    public static class ViewHolder {
        public CheckedTextView ctvStudent;
    }

}